import { request, isLoggedIn } from '../utils/request'

// 登录接口
export const login = async (username, password) => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟登录验证 - 实际项目中应该调用真实的API
    if (username === 'admin' && password === 'admin123') {
      const token = btoa(`${username}:${password}`)
      localStorage.setItem('token', token)
      isLoggedIn.value = true
      
      return { 
        success: true, 
        message: '登录成功',
        data: { token }
      }
    } else {
      return { 
        success: false, 
        message: '用户名或密码错误' 
      }
    }
  } catch (error) {
    console.error('Login failed:', error)
    return { success: false, message: error.message }
  }
}

// 登出接口
export const logout = async () => {
  try {
    const result = await request('/api/auth/logout', {
      method: 'POST'
    })
    
    localStorage.removeItem('token')
    isLoggedIn.value = false
    
    return result
  } catch (error) {
    console.error('Logout failed:', error)
    localStorage.removeItem('token')
    isLoggedIn.value = false
    return { success: false, message: error.message }
  }
}

// 检查token有效性
export const checkToken = async () => {
  try {
    const result = await request('/api/auth/check')
    return result.success
  } catch (error) {
    console.error('Token check failed:', error)
    return false
  }
}

// 导出状态管理函数
export { isLoggedIn, checkLoginStatus, getToken, clearToken } from '../utils/request'